<template>
  <div>
    <el-upload
      v-bind="{ ...item }"
      :action="item!.action"
      :before-upload="newBeforeUpload"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :on-success="uploadSuccess"
      :on-progress="handleProgress"
      :on-error="handleError"
      list-type="picture-card"
      ref="imageUploadRef"
    >
      <el-icon>
        <ele-Plus />
      </el-icon>
    </el-upload>
    <el-image-viewer
      v-if="showViewer"
      :z-index="9999"
      @close="handleCloseImageViewer"
      :initial-index="showImageIndex"
      :url-list="urlList"
    />
  </div>
</template>

<script setup name="TImageUpload" lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { formEmits, formItemProps } from "../hooks/useFormItemHook";
import { useUploadHook } from "@/views/formgen/components/FormItem/hooks/useUploadHook";
import { useWatermarkHook } from "@/views/formgen/components/FormItem/hooks/useWatermarkHook";
import Compressor from "compressorjs";

const props = defineProps({
  ...formItemProps
});

const emits = defineEmits(formEmits);

const {
  changeValue,
  initFileList,
  fileList,
  beforeUpload,
  handleRemove,
  handleExceed,
  uploadSuccess,
  handleProgress,
  handleError
} = useUploadHook(props, emits);

const { addWatermark } = useWatermarkHook();

const showViewer = ref(false);
const showImageIndex = ref(0);

const urlList = computed(() => {
  return changeValue.value.map((item: any) => item.url);
});

if (props.mode === "design") {
  watch(
    () => props.value,
    () => {
      initFileList();
    }
  );
}

const compressImage = (file: File): Promise<File> => {
  return new Promise((resolve, reject) => {
    new Compressor(file, {
      quality: props.item?.conversionRatio || 0.8,
      success(result) {
        resolve(result as File);
      },
      error(err) {
        console.log("压缩失败" + err);
        resolve(file);
      }
    });
  });
};

const newBeforeUpload = async (file: any) => {
  const success = beforeUpload(file);
  if (!success) {
    return false;
  }

  try {
    let processedFile = file;

    // 添加水印
    if (props.item?.cameraWatermark) {
      processedFile = await addWatermark(processedFile);
    }

    // 压缩图片
    if (props.item?.openConversion) {
      processedFile = await compressImage(processedFile);
    }

    return processedFile;
  } catch (error) {
    console.error("图片处理失败:", error);
    return file;
  }
};

const handlePictureCardPreview = (file: any) => {
  // 数据回显时结构不同
  let url = file.response && file.response.data;
  if (!url) {
    url = file.url;
  }
  // 找到下标
  showImageIndex.value = changeValue.value.findIndex((item: any) => item.url === url);
  showViewer.value = true;
};

// 关闭图片预览
const handleCloseImageViewer = () => {
  showViewer.value = false;
};

const imageUploadRef = ref(null);
onMounted(() => {
  // 修改dom属性，打开相机
  if (imageUploadRef.value!.$el && props.item?.openCamera) {
    const uploadInput = imageUploadRef.value!.$el.querySelector(".el-upload__input");
    uploadInput.setAttribute("capture", "environment");
  }
  console.log(imageUploadRef.value!.$el.querySelector(".el-upload__input"));
});
</script>
